package com.gopay.scheduler.shedulerx;

import com.gopay.common.constants.scheduler.SchedulerConstants;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;

import java.util.List;

/**
 * @author 19371
 */
public class SchedulerControl {

    private volatile static SchedulerControl schedulerControl;

    private final Scheduler scheduler;

    private boolean shutdown = false;

    private SchedulerControl(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    public static SchedulerControl getSingle(Scheduler scheduler){
        if (schedulerControl == null){
            synchronized (SchedulerControl.class){
                if (schedulerControl == null){
                    schedulerControl = new SchedulerControl(scheduler);
                }
            }
        }
        return schedulerControl;
    }

    public String pause(JobKey jobKey) throws SchedulerException {
        if(!shutdown) {
            scheduler.pauseJob(jobKey);
        }else {
            return SchedulerConstants.SCHEDULER_SHUTDOWN;
        }
        return SchedulerConstants.OK;
    }

    private Trigger.TriggerState getTriggerState(String jobName) throws SchedulerException {
        List<? extends Trigger> triggersOfJob = scheduler.getTriggersOfJob(new JobKey(jobName));
        if(triggersOfJob == null || triggersOfJob.size() == 0){
            return null;
        }
        Trigger trigger = triggersOfJob.get(0);
        return scheduler.getTriggerState( trigger.getKey());
    }


    public String resume(JobKey jobKey) throws SchedulerException {
        if(shutdown) {
            return SchedulerConstants.SCHEDULER_SHUTDOWN;
        } else if(Trigger.TriggerState.PAUSED.equals(getTriggerState(jobKey.getName()))){
            scheduler.resumeJob(jobKey);
            return SchedulerConstants.OK;
        }
        return getTriggerStateName(jobKey);
    }

    
    public String trigger(JobKey jobKey) throws SchedulerException {
        if(shutdown) {
            return SchedulerConstants.SCHEDULER_SHUTDOWN;
        }else if(Trigger.TriggerState.NORMAL.equals(getTriggerState(jobKey.getName()))){
            scheduler.triggerJob(jobKey);
            return SchedulerConstants.OK;
        }
        return getTriggerStateName(jobKey);
    }

    public String fishTriggerState(String jobName) throws SchedulerException {
        Trigger.TriggerState triggerState = getTriggerState(jobName);
        if(triggerState == null){
            return null;
        }
        return triggerState.name();
    }

    private String getTriggerStateName(JobKey jobKey) throws SchedulerException {
        Trigger.TriggerState triggerState = getTriggerState(jobKey.getName());
        if(triggerState != null){
            return triggerState.name();
        }else {
            return SchedulerConstants.SCHEDULER_NOT_FUND;
        }
    }

}
